import Vue from 'vue'
import stringify from "@/utils/querystring";
import cookie from "@/utils/cookie";

export function navigateTo(location, complete, fail, success) {
	handleLoginStatus(location, complete, fail, success).then(params => {
		uni.navigateTo(params)
	}).catch(error => {
		// 没有权限

	})
}

export function redirectTo(location, complete, fail, success) {
	handleLoginStatus(location, complete, fail, success).then(params => {

		uni.redirectTo(params)
	}).catch(error => {
		// 没有权限

	})
}

export function reLaunch(location, complete, fail, success) {
	handleLoginStatus(location, complete, fail, success).then(params => {

		uni.reLaunch(params)
	}).catch(error => {
		// 没有权限

	})
}

// 非负，取负会有问题，在内嵌iframe的页面，导致返回到iframe
export function navigateBack(delta) {
	let newdelta = delta ? delta : 1;
	uni.navigateBack({
		delta: newdelta
	});
}

export function switchTab(location, complete, fail, success) {
	handleLoginStatus(location, complete, fail, success).then(params => {
		uni.switchTab(params)
	}).catch(error => {
		// 没有权限
	})
}


export const router = {
	switchTab,
	navigateBack,
	reLaunch,
	redirectTo,
	navigateTo
}

export function parseUrl(location) {
	// console.log("执行了parseUrl")
	// console.log(location)
	if (typeof location === 'string') return location
	const {
		path,
		query
	} = location
	// console.log('轉換前：',query)
	// ？a=b&b=c
	const queryStr = stringify(query)
	// console.log('轉換後：',queryStr)

	if (!queryStr) {
		return path
	}

	return `${path}?${queryStr}`
}

export function auth() {
	/**
	 *	如何判断权限?
	 *	用户如果登录了系统，会留下两个东西，一个是token，一个是userInfo
	 *	token存在会过期的问题，如果长时间没有打开小程序，会导致登录失效，出现打开一个页面瞬间跳转到授权页面的问题
	 *		解决办法，保存token的时候加上过期时间，每次请求都取一下缓存里的token
	 *	userInfo只是用来限时用户信息，作用并不是很大
	 * 	ps：只需要判断 token 是否存在即可
	 */
	if (cookie.get('token')) {
		return true
	}
	return false
}

export const handleLoginStatus = (location, complete, fail, success) => {
	// 不登录可访问的页面
	let page = [{
			path: '/pages/index/index',
			name: '首页'
		},{
			path: '/pages/index/starIndex',
			name: '首页'
		},{
			path: '/pages/index/login',
			name: '登录页面'
		},
		{
			path: '/pages/index/blindDetail',
			name: '盲盒详情'
		},
		{
			path: '/pages/login/phone',
			name: '手机号注册页面'
		},
		{
			path: '/pages/index/webview',
			name: 'webview'
		}
	]

	// 是否可以访问
	let isAuth = false

	// console.log('即将跳转', location, parseUrl(location))
	// 从 location 中获取当前url，location typeof string || object
	let path = ''
	if (typeof location === 'string') {
		path = location
	} else {
		path = location.path
	}

	// 判断用户是否有token
	if (!auth()) {
		page.map((item) => {
			if (item.path == path) {
				isAuth = true
			}
		})
	} else {
		isAuth = true
	}
	// console.log("这是token:"+cookie.get('token'))
	return new Promise((resolve, reject) => {
		if (isAuth) {
			// 有token
			resolve({
				url: parseUrl(location),
				complete,
				fail,
				success
			})
		} else {
			// 没有token
			// console.log(parseUrl(location))
			// console.log("addddddddddddddddddddddd")
			routerPermissions(parseUrl(location))
			reject()
		}
	}).catch(error => {
		console.log(error)
	})
}

export function routerPermissions(url, type) {
	console.log('routerPermissions', url)
	let path = url
	if (!path) {
		path = '/' + getCurrentPageUrlWithArgs()
	}
	console.log("执行了强制跳转登录")
	uni.reLaunch({
		url: '/pages/index/login',
	})
	// cookie.set('redirect', path)
}

//判断浏览器是否是微信浏览器
export const checkIsWechatBrowser = () => {
	return (
		navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
		"micromessenger"
	);
}

//微信浏览器中打开H5隐藏顶部导航方法
export const hidePageNavInWechatBrowser = () => {
	//#ifdef H5
	if (checkIsWechatBrowser()) {
		let pageNav = document.getElementsByTagName("uni-page-head");
		if (pageNav && pageNav[0]) {
			pageNav[0].style.display = "none";
		}
	}
	//#endif
}
//用来判断是否是微信内置的浏览器
export const isWechat = () => {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
//手机号验证
export const checkMobile = (mobile) => {
	return RegExp("^[1][3-9][0-9]{9}$").test(mobile);
}
//时间戳转换成时间
export const timestampToTime = (value,type) => {
	if(value==0){
		return value;
	}
	var date = '';
	var lenth = (value + '').length;
	value = parseInt(value);
	// if(typeof value ==='string'){
	//     value=Number(value);
	// }
	// if(typeof value !=='number') {
	// 	uni.showToast({
	// 		title: '输入参数无法识别为时间戳',
	// 		icon:'none',
	// 		duration: 2000
	// 	});
	// 	return;
	// }
	//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	if (lenth == 10) date = new Date(value * 1000);
	else if (lenth == 13) date = new Date(value);
	var Y = date.getFullYear()
	var M = '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
	var D = '-' + (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
	var h = ' ' + (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours())
	var m = ':' + (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
	var s = ':' + (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
	if(type=='year'){
		return Y;
	}else if(type=='mouth'){
		return Y + M;
	}else if(type=='day'){
		return Y + M + D;
	}else if(type=='hour'){
		return Y + M + D + h;
	}else if(type=='minute'){
		return Y + M + D + h + m;
	}else if(type=='describe'){
		return Y + M + D + h + m + s;
	}
}
//截取地址栏参数
export const getUrl = (key) => {
	var url = location.href; //首先获取url
	if (url.indexOf("?") != -1) { //判断是否有参数
		var strSub = null;
		var str = url.split("?"); //根据？截取url
		var strs = str[1].split("&"); //str[1]为获取？号后的字符串，并且根据&符号进行截取，得到新的字符串数组，这个字符串数组中有n个key=value字符串
		for (var i = 0; i < strs.length; i++) { //遍历字符串数组
			strSub = strs[i].split("="); //取第i个key=value字符串，并用“=”截取获得新的字符串数组 这个数组里面第0个字符是key，第1个字符value
			if (strSub[0] == key) { //判断第0个字符与该方法的参数key是否相等，如果相等 则返回对应的值value。
				return strSub[1];
			}
		}
	}
	return "";
}
/* 部分隐藏处理
 ** str 需要处理的字符串
 ** frontLen 保留的前几位
 ** endLen 保留的后几位
 ** cha 替换的字符串
 */
export const plusXing = (str, frontLen, endLen, cha) => {
	let len = str.length - frontLen - endLen;
	let xing = "";
	for (let i = 0; i < len; i++) {
		xing += cha;
	}
	return (
		str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
	);
}

// 函数防抖
export const debounce = (fn, t) =>{
	let delay = t || 1000;
	let timer;
	return function () {
	    let args = arguments;
	    if (timer) clearTimeout(timer);
	    let callNow = !timer;
	    timer = setTimeout(() => {
	      timer = null;
		  // fn.apply(this, args);//这段代码只执行时间段内的最后一次点击
	    }, delay)
	
	    if (callNow) fn.apply(this, args) //这段代码只执行时间段内的第一次
	}
}
// 函数节流
export const throttle = (fn, t) =>{
	let last;
	let timer;
	let interval = t || 500;
	return function () {
	    let args = arguments;
	    let now = +new Date();
	    if (last && now - last < interval) {
	      clearTimeout(timer);
	      timer = setTimeout(() => {
	        last = now;
	        fn.apply(this, args);
	      }, interval);
	    } else {
	      last = now;
	      fn.apply(this, args);
	    }
	}
}
// 金额单位换算，分改为元
export const priceInteger = (price) => {
	price=parseInt(price)
	return (price/100).toFixed(2);
}
